<?php

namespace app\controllers\admin\uni\order;

use app\controllers\admin\base\AdminController;
use app\models\comment\Comment as Model;
use app\models\order\Order;
use yii\helpers\Html;

class CommentController extends AdminController
{
    public function actionList()
    {
        $order_id = $this->post('id');
        $user_id = $this->post('user_id');

        $page = intval($this->post('page', $this->page));
        $page_size = intval($this->post('pageSize', $this->pageSize));

        $query = Model::find()
            ->where(['order_id' => $order_id])
            ->with(['images', 'images.image', 'user']);

        if ($user_id) {
            $query->andWhere(['user_id' => $user_id]);
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $page_size);

        $list = $query->offset(($page - 1) * $page_size)
            ->limit($page_size)
            ->asArray()
            ->all();

        foreach ($list as &$item) {
            // content
            $item['content'] = Html::decode($item['content']);

            // images
            $i = [];
            if ($item['images']) {
              foreach ($item['images'] as $image) {
                  array_push($i, $image['image']['path']);
              }
            }
            $item['path'] = $i;

            // user
            if ($item['user']['nickname']) {
                $item['user']['nickname'] = base64_decode($item['user']['nickname']);
            }
        }

        return $this->success([
            $this->totalCount   => $totalCount,
            $this->totalPage    => $totalPage,
            $this->list         => $list,
        ]);

    }

    public function actionCheck()
    {
        $id = $this->post('id');
        $model = Model::findOne(['id' => $id]);
        if ($model) {
            $model->check = 1;
            $model->save();
            return $this->success();
        }

        return $this->fail();
    }

    public function actionReject()
    {
        $id = $this->post('id');
        $model = Model::findOne(['id' => $id]);
        if ($model) {
            $model->check = -1;
            $model->save();
            return $this->success();
        }

        return $this->fail();
    }

    public function actionBatchCheck()
    {
        $ids = $this->post('ids');

        try {
            Model::updateAll(['check' => 1], ['id' => $ids]);

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('审核错误: ' . $e->getMessage());
        }
    }

    public function actionBatchReject()
    {
        $ids = $this->post('ids');

        try {
            Model::updateAll(['check' => -1], ['id' => $ids]);

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('驳回错误: ' . $e->getMessage());
        }
    }
}